<template>
  <div class="multi-row-layout">
    <!-- 外层容器：统一控制整体间距 -->
    <el-row :gutter="16" class="main-container">
      <el-col :span="24">
        <!-- 第一行：总用量 + 漏耗指标 -->
        <el-row :gutter="16" class="content-row">
          <!-- 总用量卡片（原有逻辑保留） -->
          <el-col :span="8" :xs="24">
            <el-card
                class="stats-card"
                shadow="hover"
                :body-style="{ padding: '16px' }"
                :header-style="cardHeaderStyle"
            >
              <template #header>
                <div class="card-header-flex">
                  <span>总用量</span>
                  <el-button
                      type="primary"
                      size="mini"
                      @click="refreshHomepageData"
                      icon="Refresh"
                  >
                    重新计算
                  </el-button>
                </div>
              </template>
              <el-row :gutter="15">
                <!-- 日用水量 -->
                <el-col :span="8">
                  <div class="stats-item">
                    <div class="text-group">
                      <div class="title">日用水量</div>
                      <div class="value">{{ currentDayUsage }} <span class="unit">万吨</span></div>
                      <div class="trend">
                        <el-row class="trend-row">
                          <span>环比上月</span>
                          <el-tag
                              :type="dayMonthBias < 0 ? 'success' : 'danger'"
                              class="trend-tag"
                              :icon="dayMonthBias < 0 ? ArrowDown : ArrowUp"
                          >
                            {{ dayMonthBias > 0 ? '+' : '' }}{{ dayMonthBias }}%
                          </el-tag>
                        </el-row>
                        <el-row class="trend-row">
                          <span>同比去年</span>
                          <el-tag
                              :type="dayYearBias < 0 ? 'success' : 'danger'"
                              class="trend-tag"
                              :icon="dayYearBias < 0 ? ArrowDown : ArrowUp"
                          >
                            {{ dayYearBias > 0 ? '+' : '' }}{{ dayYearBias }}%
                          </el-tag>
                        </el-row>
                      </div>
                    </div>
                  </div>
                </el-col>
                <!-- 月用水量 -->
                <el-col :span="8">
                  <div class="stats-item">
                    <div class="text-group">
                      <div class="title">月用水量</div>
                      <div class="value">{{ currentMonthUsage }} <span class="unit">万吨</span></div>
                      <div class="trend">
                        <el-row class="trend-row">
                          <span>环比上月</span>
                          <el-tag
                              :type="monthMonthBias < 0 ? 'success' : 'danger'"
                              class="trend-tag"
                              :icon="monthMonthBias < 0 ? ArrowDown : ArrowUp"
                          >
                            {{ monthMonthBias > 0 ? '+' : '' }}{{ monthMonthBias }}%
                          </el-tag>
                        </el-row>
                        <el-row class="trend-row">
                          <span>同比去年</span>
                          <el-tag
                              :type="monthYearBias < 0 ? 'success' : 'danger'"
                              class="trend-tag"
                              :icon="monthYearBias < 0 ? ArrowDown : ArrowUp"
                          >
                            {{ monthYearBias > 0 ? '+' : '' }}{{ monthYearBias }}%
                          </el-tag>
                        </el-row>
                      </div>
                    </div>
                  </div>
                </el-col>
                <!-- 年用水量 -->
                <el-col :span="8">
                  <div class="stats-item">
                    <div class="text-group">
                      <div class="title">年用水量</div>
                      <div class="value">{{ currentYearUsage }} <span class="unit">万吨</span></div>
                      <div class="trend">
                        <el-row class="trend-row">
                          <span>同比去年</span>
                          <el-tag
                              :type="yearYearBias < 0 ? 'success' : 'danger'"
                              class="trend-tag"
                              :icon="yearYearBias < 0 ? ArrowDown : ArrowUp"
                          >
                            {{ yearYearBias > 0 ? '+' : '' }}{{ yearYearBias }}%
                          </el-tag>
                        </el-row>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>

          <!-- 漏耗指标卡片（支持本月和今年切换） -->
          <el-col :span="16" :xs="24">
            <el-card
                class="stats-card"
                shadow="hover"
                header="漏耗指标"
                :body-style="{ padding: '16px' }"
                :header-style="cardHeaderStyle"
            >
              <el-row :gutter="10" class="vertical-menu-container">
                <el-col :span="3" :xs="6">
                  <el-menu
                      v-model="leakageActiveType"
                      class="vertical-menu"
                      mode="vertical"
                      background-color="transparent"
                      border-right="none"
                      @select="handleMenu2Select"
                      :style="{ '--menu-item-height': '40px' }"
                  >
                    <el-menu-item index="year" class="menu-item">今年</el-menu-item>
                    <el-menu-item index="month" class="menu-item">本月</el-menu-item>
                  </el-menu>
                  <el-button type="text" class="more-btn" @click="handleMore2">更多详情</el-button>
                </el-col>
                <el-col :span="21" :xs="18">
                  <el-row :gutter="10" class="metric-gauge-row">
                    <el-col :span="16" :xs="24">
                      <div class="metric-panel">
                        <div
                            class="metric-item"
                            v-for="(item, idx) in metricList"
                            :key="`metric-${idx}`"
                        >
                          <div class="metric-text">
                            <span class="metric-title">{{ item.title }}</span>
                            <span class="metric-value">{{ item.value }} 万吨</span>
                          </div>
                          <el-progress
                              :percentage="item.progress"
                              :stroke-width="6"
                              :color="item.color"
                              class="metric-progress"
                          />
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="8" :xs="24">
                      <div class="gauge-panel">
                        <el-row :gutter="10" type="flex" justify="center">
                          <el-col :span="24" :xs="24">
                            <div class="gauge-card">
                              <div class="gauge-title">{{ gaugeList[0].title }}</div>
                              <el-progress
                                  type="circle"
                                  :percentage="gaugeList[0].percent"
                                  :stroke-width="8"
                                  :color="gaugeList[0].color"
                                  class="gauge-chart"
                              >
                                <template #indicator>
                                  <div class="gauge-label">
                                    <span class="gauge-number">{{ gaugeList[0].number }}%</span>
                                  </div>
                                </template>
                              </el-progress>
                            </div>
                          </el-col>
                        </el-row>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <!-- 第二行：用水量排名 + 最小流量排名 -->
        <el-row :gutter="16" class="content-row">
          <!-- 用水量排名 -->
          <el-col :span="8" :xs="24">
            <el-card
                class="ranking-card"
                shadow="hover"
                header="用水量排名"
                :body-style="{ padding: '5px' }"
                :header-style="cardHeaderStyle"
            >
              <el-row :gutter="12" class="ranking-menu-row">
                <el-col :span="5" :xs="8" class="menu-vertical-col">
                  <el-menu
                      v-model="activeRankType"
                      class="vertical-menu fill-vertical-menu"
                      mode="vertical"
                      background-color="transparent"
                      border-right="none"
                      @select="handleMenu1Select"
                      :style="{ '--menu-item-height': '50px' }"
                  >
                    <el-menu-item index="month" class="menu-item">本月</el-menu-item>
                    <el-menu-item index="yesterday" class="menu-item">昨日</el-menu-item>
                  </el-menu>
                  <el-button type="text" class="more-btn menu-more-btn" @click="handleMore1">更多详情</el-button>
                </el-col>
                <el-col :span="19" :xs="16">
                  <div class="ranking-list">
                    <div
                        class="ranking-item"
                        v-for="(item, idx) in waterRankingList"
                        :key="`water-rank-${idx}`"
                    >
                      <el-tag class="rank-tag" :class="`rank-tag--${item.rank}`">TOP{{ item.rank }}</el-tag>
                      <span class="unit-name">{{ item.name }}</span>
                      <span class="unit-value">{{ item.value }} 吨</span>
                    </div>
                    <div v-if="waterRankingList.length === 0" class="no-data">暂无数据</div>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>

          <!-- 最小流量排名 -->
          <el-col :span="16" :xs="24">
            <el-card
                class="ranking-card"
                shadow="hover"
                header="最小流量排名"
                :body-style="{ padding: '16px' }"
                :header-style="cardHeaderStyle"
            >
              <el-row :gutter="10">
                <!-- 最小流量排名列表 -->
                <el-col :span="11" :xs="24">
                  <div class="ranking-list">
                    <div
                        class="ranking-item clickable-item"
                        v-for="(item, idx) in minFlowRankingList"
                        :key="`night-rank-${idx}`"
                        @click="handleMinFlowItemClick(item)"
                    >
                      <el-tag class="rank-tag" :class="`rank-tag--${item.rank}`">TOP{{ item.rank }}</el-tag>
                      <span class="unit-name">{{ item.name }}</span>
                      <span class="unit-value">{{ item.value }} 吨</span>
                    </div>
                    <div v-if="minFlowRankingList.length === 0" class="no-data">暂无数据</div>
                  </div>
                  <el-button type="text" class="more-btn center-btn" @click="handleMore3">更多详情</el-button>
                </el-col>

                <!-- 图表区域 -->
                <el-col :span="13" :xs="24">
                  <div class="chart-wrapper">
                    <ECharts :option="chartOptions" style="width: 100%; height: 260px;" />
                  </div>
                  <el-date-picker
                      v-model="dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 220px; margin: 12px auto; display: block;"
                      @change="handleDateChange"
                      :picker-options="{ shortcuts: [{ text: '近7天', onClick: () => setShortcutDate(7) }] }"
                  />
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <!-- 第三行：用水趋势统计图表 -->
        <el-row :gutter="16" class="content-row">
          <el-col :span="24">
            <el-card
                class="chart-card"
                shadow="hover"
                header="用水趋势统计"
                :body-style="{ padding: '5px' }"
                :header-style="cardHeaderStyle"
            >
              <div class="chart-container">
                <el-row :gutter="16" class="chart-row">
                  <!-- 年用水趋势 -->
                  <el-col :span="10" :xs="24">
                    <div class="chart-wrapper">
                      <ECharts :option="yearChart" style="width: 100%; height: 240px;" />
                    </div>
                  </el-col>
                  <!-- 月用水趋势 -->
                  <el-col :span="14" :xs="24">
                    <div class="chart-wrapper">
                      <ECharts :option="monthChart" style="width: 100%; height: 240px;" />
                    </div>
                  </el-col>
                </el-row>
                <el-row class="chart-row" style="margin-top: 16px;">
                  <!-- 日用水趋势 -->
                  <el-col :span="24">
                    <div class="chart-wrapper">
                      <ECharts :option="dayChart" style="width: 100%; height: 240px;" />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="WaterDashboard">
// 1. 核心依赖引入
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import {
  ElCard, ElRow, ElCol, ElButton, ElMenu, ElMenuItem,
  ElTag, ElProgress, ElDatePicker, ElMessage
} from 'element-plus';
import { ArrowDown, ArrowUp, Refresh } from '@element-plus/icons-vue';
import ECharts from '@/components/ECharts/index.vue';
// 引入接口
import { listHomepage, calculateHomepage } from '@/api/water/homepage';
import { listMeterAnalyse } from '@/api/water/meterAnalyse';

// 2. 基础状态变量
const version = ref('3.9.0');
const dateRange = ref([]); // 日期范围（默认近7天）
const cardHeaderStyle = ref({
  padding: '12px 16px',
  fontSize: '16px',
  borderBottom: '1px solid #f2f2f2'
});
const router = useRouter();
// 记录选中的最小流量排名水表名称（默认TOP1）
const selectedMeterName = ref('');

// 3. homepage数据存储
const homepageData = ref({}); // key: valueCode, value: homepage实体
const currentDayUsage = ref('0.00'); // 昨日用量（dayTotalUsage_昨日日期）
const currentMonthUsage = ref('0.00'); // 本月用量（monthUsage_当前月）
const currentYearUsage = ref('0.00'); // 本年用量（yearUsage_当前年）
const dayMonthBias = ref('0.00'); // 昨日环比上月
const dayYearBias = ref('0.00'); // 昨日同比去年
const monthMonthBias = ref('0.00'); // 本月环比上月
const monthYearBias = ref('0.00'); // 本月同比去年
const yearYearBias = ref('0.00'); // 本年同比去年
const currentYear = ref(dayjs().year());
const currentMonth = ref(dayjs().month() + 1); // dayjs月份0-11→1-12
const yesterdayDay = ref(dayjs().subtract(1, 'day').date()); // 昨日日期
const lastMonth = ref(currentMonth.value === 1 ? 12 : currentMonth.value - 1); // 上月

// 4. 排名相关变量
const activeRankType = ref('month'); // 用水量排名类型
const waterRankingList = ref([]); // 用水量排名列表
const minFlowRankingList = ref([]); // 最小流量排名列表

// 5. 漏耗指标相关变量
const leakageActiveType = ref('month'); // 漏耗指标类型：month-本月，year-今年
const metricList = ref([
  { title: '一级表（本月）', value: 0, progress: 0, color: '#87E8DE' },
  { title: '二级表（本月）', value: 0, progress: 0, color: '#FF6B6B' },
]);
const gaugeList = ref([
  { title: '一级漏耗', number: 0, percent: 0, color: '#AED581' }
]);

// 6. 图表配置
const chartOptions = ref({
  xAxis: {
    type: 'category',
    data: [], // 初始空数据（接口返回后填充）
    axisLabel: { rotate: 30 } // 日期标签旋转避免重叠
  },
  yAxis: {
    type: 'value',
    name: '最小流量（吨）',
    min: 0 // 最小流量不能为负
  },
  grid: { left: '5%', right: '5%', bottom: '15%', top: '5%' }, // 调整间距
  series: [{
    data: [], // 初始空数据（接口返回后填充）
    type: 'line',
    smooth: true,
    itemStyle: { color: '#42a5f5' }, // 线条颜色
    lineStyle: { width: 2 }
  }],
  tooltip: {
    trigger: 'axis',
    formatter: (params) => `${params.seriesName}<br/>${params.name}：${params.value} 吨`
  },
  // 无数据提示
  noDataLoadingOption: {
    text: '暂无数据',
    textStyle: { fontSize: 14, color: '#999' },
    effect: 'bubble'
  }
});
// 其他趋势图表
const yearChart = ref({
  title: { text: '年用水量', left: '10px', fontSize: 14, top: '0' },
  grid: { left: '5%', right: '5%', bottom: '0%', top: '25%' },
  xAxis: { type: 'category', data: [] },
  yAxis: { type: 'value', name: '万吨' },
  series: [{ name: '用量', type: 'bar', data: [], itemStyle: { color: '#56add9' } }]
});
const monthChart = ref({
  title: { text: `月用水量（${currentYear.value}年）\n{b|累计：} {a|0.00万吨}`, left: '10px', fontSize: 14, top: '0', textStyle: { rich: { a: { fontSize: 16, fontWeight: 'bold' }, b: { fontSize: 14 } } } },
  grid: { left: '5%', right: '5%', bottom: '0%', top: '30%' },
  xAxis: { type: 'category', data: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'] },
  yAxis: { type: 'value', name: '万吨' },
  series: [{ name: '今年', type: 'bar', data: [], itemStyle: { color: 'rgb(86,173,217)' } }]
});
const dayChart = ref({
  title: { text: `日用水量（${currentYear.value}年${currentMonth.value}月）\n{b|累计：} {a|0.00万吨}`, left: '10px', fontSize: 14, top: '0', textStyle: { rich: { a: { fontSize: 16, fontWeight: 'bold' }, b: { fontSize: 14 } } } },
  grid: { left: '5%', right: '5%', bottom: '10%', top: '30%' },
  xAxis: { type: 'category', data: [] },
  yAxis: { type: 'value', name: '万吨' },
  series: [
    { name: '本月', type: 'bar', data: [], itemStyle: { color: '#56add9' } },
    { name: '上月', type: 'line', data: [], itemStyle: { color: '#FAB637' } }
  ]
});

// 7. 更新排名列表数据
const updateRankingLists = () => {
  // 用水量排名
  const waterRankKeys = activeRankType.value === 'month'
      ? ['monthUsageTop1', 'monthUsageTop2', 'monthUsageTop3', 'monthUsageTop4', 'monthUsageTop5', 'monthUsageTop6']
      : ['usageTop1', 'usageTop2', 'usageTop3', 'usageTop4', 'usageTop5', 'usageTop6'];
  waterRankingList.value = waterRankKeys
      .filter(key => homepageData.value[key])
      .map((key, idx) => ({
        name: homepageData.value[key].key,
        value: Number(homepageData.value[key].value),
        rank: idx + 1
      }));

  // 最小流量排名
  const minFlowRankKeys = ['minValTop1', 'minValTop2', 'minValTop3', 'minValTop4', 'minValTop5', 'minValTop6'];
  minFlowRankingList.value = minFlowRankKeys
      .filter(key => homepageData.value[key])
      .map((key, idx) => ({
        name: homepageData.value[key].key,
        value: Number(homepageData.value[key].value),
        rank: idx + 1
      }));
};

// 8. 计算漏耗数据
const calculateLeakageData = () => {
  let level1Value, level2Value, title1, title2;

  // 步骤1：定义分类型的参考值配置（可根据业务需求调整数值）
  const referenceConfig = {
    month: { level1: 100000, level2: 80000 }, // 本月参考值：一级表10万、二级表8万
    year: { level1: 1200000, level2: 960000 }  // 今年参考值：一级表120万、二级表96万（10倍于本月）
  };

  if (leakageActiveType.value === 'month') {
    // 本月数据
    title1 = '一级表（本月）';
    title2 = '二级表（本月）';
    level1Value = homepageData.value['monthLeakageLevel_1'] ? Number(homepageData.value['monthLeakageLevel_1'].value) : 0;
    level2Value = homepageData.value['monthLeakageLevel_2'] ? Number(homepageData.value['monthLeakageLevel_2'].value) : 0;
  } else {
    // 今年数据
    title1 = '一级表（今年）';
    title2 = '二级表（今年）';
    level1Value = homepageData.value['yearLeakageLevel_1'] ? Number(homepageData.value['yearLeakageLevel_1'].value) : 0;
    level2Value = homepageData.value['yearLeakageLevel_2'] ? Number(homepageData.value['yearLeakageLevel_2'].value) : 0;
  }

  // 计算漏耗量和漏耗比（原有逻辑不变）
  const leakageValue = Math.max(0, level1Value - level2Value);
  const leakageRatio = level1Value > 0 ? (leakageValue / level1Value * 100).toFixed(2) : 0;

  // 步骤2：根据当前类型获取对应参考值
  const currentRef = referenceConfig[leakageActiveType.value];

  // 步骤3：用对应参考值计算进度条（替换原固定值）
  metricList.value = [
    {
      title: title1,
      value: (level1Value / 10000).toFixed(2), // 转换为万吨（原有逻辑不变）
      progress: Math.min(100, (level1Value / currentRef.level1) * 100), // 用当前类型的一级表参考值
      color: '#87E8DE'
    },
    {
      title: title2,
      value: (level2Value / 10000).toFixed(2), // 转换为万吨（原有逻辑不变）
      progress: Math.min(100, (level2Value / currentRef.level2) * 100), // 用当前类型的二级表参考值
      color: '#FF6B6B'
    }
  ];

  // 漏耗比仪表盘（原有逻辑不变）
  gaugeList.value = [{
    title: '一级漏耗',
    number: leakageRatio,
    percent: Math.min(100, Number(leakageRatio)),
    color: leakageRatio > 30 ? '#FF6B6B' : leakageRatio > 15 ? '#FFB74D' : '#AED581'
  }];
};

// 9. 处理homepage数据
const handleHomepageData = (list) => {
  list.forEach(item => {
    homepageData.value[item.valueCode] = item;
  });

  // 提取用量数据（吨→万吨）
  const dayCode = `dayTotalUsage_${yesterdayDay.value}`;
  currentDayUsage.value = homepageData.value[dayCode] ? (homepageData.value[dayCode].value / 10000).toFixed(2) : '0.00';
  const monthCode = `monthUsage_${currentMonth.value}`;
  currentMonthUsage.value = homepageData.value[monthCode] ? (homepageData.value[monthCode].value / 10000).toFixed(2) : '0.00';
  const yearCode = `yearUsage_${currentYear.value}`;
  currentYearUsage.value = homepageData.value[yearCode] ? (homepageData.value[yearCode].value / 10000).toFixed(2) : '0.00';

  // 提取偏差数据
  dayMonthBias.value = homepageData.value.dayMonthBias ? Number(homepageData.value.dayMonthBias.value).toFixed(2) : '0.00';
  dayYearBias.value = homepageData.value.dayYearBias ? Number(homepageData.value.dayYearBias.value).toFixed(2) : '0.00';
  monthMonthBias.value = homepageData.value.monthMonthBias ? Number(homepageData.value.monthMonthBias.value).toFixed(2) : '0.00';
  monthYearBias.value = homepageData.value.monthYearBias ? Number(homepageData.value.monthYearBias.value).toFixed(2) : '0.00';
  yearYearBias.value = homepageData.value.yearYearBias ? Number(homepageData.value.yearYearBias.value).toFixed(2) : '0.00';

  // 计算漏耗指标
  calculateLeakageData();

  // 更新排名列表
  updateRankingLists();

  // 更新趋势图表
  updateCharts();
};

// 10. 更新趋势图表数据
const updateCharts = () => {
  // 年图表
  const yearLabels = [];
  const yearData = [];
  for (let i = 5; i >= 0; i--) {
    const year = currentYear.value - i;
    yearLabels.push(`${year}年`);
    const yearCode = `yearUsage_${year}`;
    const usage = homepageData.value[yearCode] ? (homepageData.value[yearCode].value / 10000).toFixed(2) : '0.00';
    yearData.push(Number(usage));
  }
  yearChart.value.xAxis.data = yearLabels;
  yearChart.value.series[0].data = yearData;

  // 月图表
  const monthData = [];
  for (let i = 1; i <= 12; i++) {
    const monthCode = `monthUsage_${i}`;
    const usage = homepageData.value[monthCode] ? (homepageData.value[monthCode].value / 10000).toFixed(2) : '0.00';
    monthData.push(Number(usage));
  }
  monthChart.value.series[0].data = monthData;
  const monthTotal = monthData.slice(0, currentMonth.value).reduce((sum, val) => sum + val, 0).toFixed(2);
  monthChart.value.title.text = `月用水量（${currentYear.value}年）\n{b|累计：} {a|${monthTotal}万吨}`;

  // 日图表
  const dayLabels = [];
  const currentDayData = [];
  const lastDayData = [];
  const currentMonthDays = dayjs(`${currentYear.value}-${currentMonth.value}`).daysInMonth();
  const lastMonthDays = dayjs(`${currentYear.value}-${lastMonth.value}`).daysInMonth();

  for (let i = 1; i <= 31; i++) {
    dayLabels.push(`${i}日`);
    const currentCode = `dayTotalUsage_${i}`;
    currentDayData.push(i <= currentMonthDays ? (homepageData.value[currentCode] ? (homepageData.value[currentCode].value / 10000).toFixed(2) : '0.00') : '0.00');
    const lastCode = `monthagoDayTotalUsage_${i}`;
    lastDayData.push(i <= lastMonthDays ? (homepageData.value[lastCode] ? (homepageData.value[lastCode].value / 10000).toFixed(2) : '0.00') : '0.00');
  }

  dayChart.value.xAxis.data = dayLabels;
  dayChart.value.series[0].data = currentDayData.map(Number);
  dayChart.value.series[1].data = lastDayData.map(Number);
  const dayTotal = currentDayData.slice(0, yesterdayDay.value).reduce((sum, val) => sum + Number(val), 0).toFixed(2);
  dayChart.value.title.text = `日用水量（${currentYear.value}年${currentMonth.value}月）\n{b|累计：} {a|${dayTotal}万吨}`;
};

// 11. 重新计算+刷新数据
const refreshHomepageData = async () => {
  try {
    await calculateHomepage();
    const res = await listHomepage({ valueTypeList: [1, 2, 3, 4, 5] });
    if (res.rows && res.rows.length > 0) {
      handleHomepageData(res.rows);
      // 重新加载后重置选中水表并查询
      if (minFlowRankingList.value.length > 0) {
        selectedMeterName.value = minFlowRankingList.value[0].name;
        fetchMeterAnalyseData();
      }
    }
    ElMessage.success('用水趋势计算并刷新成功');
  } catch (error) {
    console.error('刷新用水数据失败：', error);
    ElMessage.error('刷新失败，请重试');
  }
};

// 12. 原有工具函数
const getYesterdayDate = () => {
  return dayjs().subtract(1, 'day').format('YYYY-MM-DD');
};

// 13. 最小流量排名点击事件 - 选中水表并查询数据
const handleMinFlowItemClick = (item) => {
  // 记录选中的水表名称
  selectedMeterName.value = item.name;
  // 触发接口查询
  fetchMeterAnalyseData();
};

// 14. 调用listMeterAnalyse接口 - 获取水表最小流量数据
const fetchMeterAnalyseData = async () => {
  // 1. 校验参数
  if (!selectedMeterName.value) {
    ElMessage.warning('请选择一个水表');
    return;
  }
  if (dateRange.value.length !== 2) {
    ElMessage.warning('请选择日期范围');
    return;
  }

  // 2. 处理日期格式（转YYYY-MM-DD适配后端）
  const [startDate, endDate] = dateRange.value;
  const startTime = dayjs(startDate).format('YYYY-MM-DD');
  const endTime = dayjs(endDate).format('YYYY-MM-DD');

  try {
    // 3. 调用接口（参数：水表名、开始日期、结束日期）
    const res = await listMeterAnalyse({
      meterName: selectedMeterName.value,
      startTime: startTime,
      endTime: endTime,
      pageNum: 1,
      pageSize: 100
    });

    // 4. 处理返回数据
    const analyseList = res.rows || [];
    if (analyseList.length === 0) {
      // 无数据时清空图表
      chartOptions.value.xAxis.data = [];
      chartOptions.value.series[0].data = [];
      ElMessage.info('该时间段内无最小流量数据');
      return;
    }

    // 5. 数据排序（按日期升序）
    const sortedList = [...analyseList].sort((a, b) => {
      return dayjs(a.analyseDate).valueOf() - dayjs(b.analyseDate).valueOf();
    });

    // 6. 提取图表数据（x轴：日期，y轴：当日最小流量）
    const xData = sortedList.map(item => dayjs(item.analyseDate).format('MM-DD')); // 显示“月-日”
    const yData = sortedList.map(item => {
      // 确保数值为数字（处理后端返回字符串的情况）
      return Number(item.todayMinVal) || 0;
    });

    // 7. 更新图表配置
    chartOptions.value = {
      ...chartOptions.value,
      xAxis: {
        ...chartOptions.value.xAxis,
        data: xData
      },
      series: [
        {
          ...chartOptions.value.series[0],
          data: yData,
          name: `${selectedMeterName.value}最小流量` // 系列名称（显示在tooltip）
        }
      ]
    };

  } catch (error) {
    console.error('查询水表最小流量数据失败：', error);
    ElMessage.error('数据查询失败，请重试');
    // 错误时清空图表
    chartOptions.value.xAxis.data = [];
    chartOptions.value.series[0].data = [];
  }
};

// 15. 页面初始化
onMounted(async () => {
  try {
    // 1. 加载homepage数据，包含漏耗数据的valueType=2
    const homepageRes = await listHomepage({ valueTypeList: [1, 2, 3, 4, 5] });
    if (homepageRes.data && homepageRes.data.length > 0) {
      handleHomepageData(homepageRes.data);
      // 初始化选中最小流量TOP1
      if (minFlowRankingList.value.length > 0) {
        selectedMeterName.value = minFlowRankingList.value[0].name;
      }
    }

    // 2. 默认日期范围（近7天）+ 首次查询最小流量图表
    setShortcutDate(7);
    // 确保选中水表后执行查询
    if (selectedMeterName.value) {
      await fetchMeterAnalyseData();
    }

  } catch (error) {
    console.error('页面初始化数据加载失败：', error);
  }
});

// 16. 交互方法
const handleMore1 = () => {
  router.push('/analysis/day');
};

const handleMenu1Select = (key) => {
  activeRankType.value = key;
  updateRankingLists();
};

// 漏耗指标标签切换
const handleMenu2Select = (key) => {
  leakageActiveType.value = key;
  calculateLeakageData();
};

const handleMore2 = () => {
  const yesterday = getYesterdayDate();
  router.push({ path: '/result/leakage', query: { analyseDate: yesterday } });
};

const handleMore3 = () => {
  router.push('/analysis/daymin');
};

// 日期范围变更触发重新查询
const handleDateChange = (val) => {
  console.log('日期范围变更：', val);
  fetchMeterAnalyseData();
};

const setShortcutDate = (days) => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - days * 24 * 60 * 60 * 1000);
  dateRange.value = [start, end];
};
</script>

<style scoped lang="scss">
// 卡片headerflex布局（放标题和按钮）
.card-header-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
// 可点击排名项样式（最小流量排名）
.clickable-item {
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: #f5f7fa; // hover背景色，提升交互感知
  }
}

// 图表无数据样式优化
::v-deep .echarts-nodata {
  color: #999;
  font-size: 14px;
}

// 原有样式
$gap-sm: 8px;
$gap-md: 12px;
$gap-lg: 16px;
$text-primary: #333;
$text-secondary: #666;
$text-tertiary: #999;
$card-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
$card-shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.12);

.main-container {
  padding: $gap-md;
}
.content-row {
  margin-bottom: $gap-md !important;
}

.el-card {
  border-radius: 8px !important;
  box-shadow: $card-shadow !important;
  transition: box-shadow 0.3s ease;
  min-height: 250px;

  &:hover {
    box-shadow: $card-shadow-hover !important;
  }
}

.vertical-menu {
  background-color: transparent;
  border-right: none;

  .menu-item {
    font-size: 14px;
    color: $text-secondary;
    border-radius: 6px;
    padding-block: 30%;

    &.is-active {
      background-color: #e3f2fd !important;
      color: #1976d2 !important;
    }
  }
}

.more-btn {
  font-size: 14px;
  color: #42a5f5;
  padding: 0;

  &:hover {
    color: #1976d2;
  }

  &.center-btn {
    display: block;
    margin-top:10px;
  }
  &.menu-more-btn {
    display: block;
    width: 100%;
    margin-top:10px;
    margin-bottom:10px;
  }
}

.stats-card {
  .stats-item {
    text-align: center;
    padding: $gap-sm 0;
  }
  .title {
    font-size: 14px;
    color: $text-secondary;
    margin-bottom: $gap-sm;
  }
  .value {
    font-size: 18px;
    font-weight: 600;
    color: $text-primary;
    margin-bottom: $gap-sm;

    .unit {
      font-size: 14px;
      font-weight: normal;
      color: $text-secondary;
    }
  }
  .trend {
    .trend-row {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      color: $text-secondary;
      margin-top: $gap-sm;

      .trend-tag {
        margin-left: $gap-sm;
        font-size: 12px;
        padding: 1px 6px;
      }
    }
  }

  .metric-panel {
    padding: 0;
  }
  .metric-item {
    margin-bottom: $gap-md;
  }
  .metric-text {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    margin-bottom: $gap-md;
    margin-top: $gap-md;

    .metric-title {
      font-size: 14px;
      color: $text-secondary;
    }
    .metric-value {
      font-size: 16px;
      font-weight: 500;
      color: $text-primary;
    }
  }
  .metric-progress {
    width: 100%;
  }

  .gauge-panel {
    padding: 0;
  }
  .gauge-card {
    text-align: center;
    padding: 0;
  }
  .gauge-title {
    font-size: 14px;
    color: $text-secondary;
    margin-bottom: 2px;
  }
  .gauge-chart {
    width: 120px !important;
    margin: 0;
    --el-progress-circle-track-color: #eceff1;
  }
  .gauge-label {
    position: relative;
    top: -60px;
    color: $text-primary;

    .gauge-number {
      font-size: 18px;
      font-weight: 600;
      display: block;
    }
    .gauge-change {
      font-size: 12px;
      color: $text-secondary;
    }
  }
}

.ranking-card {
  .ranking-list {
    padding: 8px;
  }
  .ranking-item {
    display: flex;
    align-items: center;
    padding: $gap-sm 0;
    font-size: 14px;

    .rank-tag {
      padding: 2px 8px;
      font-size: 12px;
      font-weight: 500;
      color: #fff;
      border: none;
      margin-right: $gap-md;
      border-radius: 4px;
    }
    .rank-tag--1 { background-color: #dc5267; }
    .rank-tag--2 { background-color: #ec9d68; }
    .rank-tag--3 { background-color: rgb(228, 200, 16); }
    .rank-tag--4 { background-color: #b8ce77; }
    .rank-tag--5 { background-color: #b0d6ba; }
    .rank-tag--6 { background-color: rgba(86, 173, 217, 0.44); }

    .unit-name {
      flex: 1;
      min-width: 0;
      color: $text-primary;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .unit-value {
      margin-left: auto;
      color: $text-secondary;
    }
  }

  .ranking-menu-row {
    display: flex;
    align-items: stretch;
    height: 100%;
    min-height: 315px;
  }
  .menu-vertical-col {
    display: flex;
    flex-direction: column;
    padding-left: 0;
  }
  .fill-vertical-menu {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .menu-item {
      padding-block: 70% !important;
    }
  }

  .chart-wrapper {
    margin-bottom: 0;
    border-radius: 6px;
    background-color: #fff;
    padding: 0;
    box-sizing: border-box;
  }
}

.chart-card {
  .chart-container {
    width: 100%;
  }
  .chart-row {
    width: 100%;
  }
  .chart-wrapper {
    width: 100%;
    border-radius: 6px;
    background-color: #fff;
    padding: $gap-sm;
    box-sizing: border-box;
  }
}

@media (max-width: 767px) {
  .main-container {
    padding: $gap-sm;
  }
  .content-row {
    margin-bottom: $gap-sm !important;
  }

  .stats-item, .ranking-item {
    padding: $gap-sm 0;
  }
  .gauge-card {
    padding: $gap-sm 0;
  }
  .gauge-chart {
    width: 100px !important;
  }
  .gauge-label {
    top: -50px;
  }

  .more-btn {
    font-size: 12px;
  }
  .chart-wrapper {
    padding: $gap-sm 0;
  }
}
</style>
